//
//  SearchResultViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/11/6.
//  Copyright © 2015年 zhixiao. All rights reserved.
//

import UIKit

class SearchResultViewController: BaseViewController {
    var displayTable:UITableView!
    var currentNumber:NSInteger = 0
    var totalNumber:NSInteger = 0
    var currentPage:NSInteger = 1
    let length:NSInteger = 12
    var keyword:String?
    var noteInfo:UILabel!
    var searchBar:UISearchBar!
    var tableDataSource:[GoodDetailItem] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "搜索结果"
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"goBack")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
        self.automaticallyAdjustsScrollViewInsets = false
        self.view.backgroundColor = UIColor.whiteColor()
        noteInfo = UILabel(frame: CGRectMake(10,74, 200,25))
        //        noteInfo.textColor = commonRedColor
        noteInfo.font = UIFont.boldSystemFontOfSize(13)
        view.addSubview(noteInfo)
        self.createTableView()
        self.queryGoodsByKeyWord(self.keyword, offset:self.currentPage, length:self.length)
        self.showProcess("正在搜索...")
        // Do any additional setup after loading the view.
    }
    func createTableView(){
        //        leftTableDataSource.addObjectsFromArray(["热门品牌","食品/保健","美妆个护","母婴用品","服饰鞋包","生活数码"])
        displayTable = UITableView(frame: CGRectMake(0, CGRectGetMaxY(noteInfo.frame)+5, view.bounds.size.width, view.bounds.size.height-CGRectGetMaxY(noteInfo.frame)-5), style: UITableViewStyle.Plain)
        displayTable.backgroundColor = UIColor.clearColor();
        displayTable.separatorStyle = UITableViewCellSeparatorStyle.None
        displayTable.showsHorizontalScrollIndicator = false
        displayTable.showsVerticalScrollIndicator = false
        displayTable.dataSource = self
        displayTable.delegate = self
        let nib2 = UINib(nibName:"GoodsListCell", bundle: nil)
        displayTable.registerNib(nib2, forCellReuseIdentifier:"GoodsListCellID")
        displayTable.footer =  MJRefreshAutoNormalFooter(refreshingBlock:{[weak self] in
                self?.currentPage++
                self?.queryGoodsByKeyWord(self?.keyword, offset:self!.currentPage, length:self!.length)
            })
        displayTable.footer.hidden = true
        view.addSubview(displayTable)
    }
    override func viewWillAppear(animated: Bool){
        super.viewWillAppear(animated)
        navigationController?.navigationBarHidden = false
    }
    func queryGoodsByKeyWord(keyString:String!,offset:Int,length:Int)->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject("", forKey: "category")
        parameters.setObject("", forKey: "orderItem")
        parameters.setObject(keyString, forKey: "query")
        parameters.setObject(NSNumber(integer: offset),forKey: "c")
        parameters.setObject(NSNumber(integer:length), forKey: "s")
        request.requestStart("/search/normal", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                }
                if let array = dic?.pareseDataToGoodListArray(){
                    let total:NSString = dic?["data"]?["productCount"] as! NSString
                    self.totalNumber = total.integerValue
                    if self.currentNumber == 0{
                        self.tableDataSource.removeAll(keepCapacity: false)
                        self.tableDataSource = array
                    }
                    else{
                        for i in 0..<array.count{
                            let obj:GoodDetailItem = array[i]
                            self.tableDataSource.append(obj)
                        }
                    }
                    self.currentNumber = self.tableDataSource.count
                }
                dispatch_async(dispatch_get_main_queue()){
                    self.noteInfo.text = NSString(format: "共有%d条符合要求的数据", self.totalNumber) as String
                    if self.currentNumber == 0{
                        self.noteInfo.text = "抱歉未能找到符合条件的数据"
                    }
                    self.displayTable.reloadData()
                    if self.currentNumber == self.totalNumber{
                        self.displayTable.footer.noticeNoMoreData()
                    }
                    else{
                        self.displayTable.footer.resetNoMoreData()
                    }
                    if self.displayTable.contentSize.height<self.displayTable.bounds.size.height{
                        self.displayTable.footer.hidden = true
                    }
                    else{
                        self.displayTable.footer.hidden = false
                    }
                }
                
            }
            else{
                dispatch_async(dispatch_get_main_queue()){
                }
            }
            
        })
    }
    func  goBack(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension SearchResultViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return  self.tableDataSource.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("GoodsListCellID", forIndexPath: indexPath) as! GoodsListCell
        let obj:GoodDetailItem? = tableDataSource[indexPath.row]
        cell.goodsImageView.setImageWithUrl(obj!.image!,defaultImage: nil)
        cell.nameLbl.text = obj?.name
        cell.priceLbl.text = "¥"+obj!.price!
        return cell;
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
        return 100
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        let ctl = GoodsDetailViewController()
        let obj:GoodDetailItem = self.tableDataSource[indexPath.row]
        ctl.goodsID = obj.id
        ctl.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(ctl, animated: true)
    }
    
}